var express = require('express');
var app = express();
// socket.io配合express使用
var http = require('http').Server(app);
var io = require('socket.io')(http);
var session = require("express-session");
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true
}));

var alluser = [];

app.set("view engine","ejs");
app.use(express.static("./public"))
app.get("/",function(req,res,next){
    res.render("index");
});
app.get("/check",function(req,res,next){        // 确认登录
    var username = req.query.username;
    if(!req.query.username){
        res.send("必须填写用户名");
        return;
    }
    if(alluser.indexOf(username) != -1){
        res.send("用户名被占用");
        return;
    }
    alluser.push(username);
    req.session.username = username;
    res.redirect("/chat");
});
app.get("/chat",function(req,res,next){ //聊天室
    if(!req.session.username){  // 保证要登录
        res.redirect("/");
        return;
    }
    res.render("chat",{
        "username": req.session.username
    });
});

io.on("connection",function(socket){
    socket.on("chat",function(msg){
        // 把接收到的msg原样广播
        io.emit("chat",msg);
    })
})

http.listen(3000);